import Foods from "./Food";
import ScroePanel from "./ScroePanel";
import Snake from "./Snake";
// 游戏控制器
class GameControl {
  // 定义三个属性
  snake: Snake;
  foods: Foods;
  scorePanel: ScroePanel;
  // 存储蛇的移动方向  按键的方向
  direction: string = '';
  // 蛇是否存活
  isLive: boolean = true;

  constructor() {
    this.foods = new Foods();
    this.scorePanel = new ScroePanel();
    this.snake = new Snake();
    this.init();
  }

  // 创建移动方法
  run() {
    /**
     * 根据方向来改变位置
     * 
     */
    // 获取蛇现在坐标
    let X = this.snake.X;
    let Y = this.snake.Y;

    switch (this.direction) {
      case "ArrowUp":
        Y -= 10;
        break;
      case "ArrowLeft":
        X -= 10;
        break;
      case "ArrowRight":
        X += 10;
        break;
      case "ArrowDown":
        Y += 10;
        break;
    }
    // 判断是否吃到食物
    this.checkFood();

    try {
      this.snake.X = X;
      this.snake.Y = Y;
    } catch (e: any) {
      this.isLive = false;
      alert(e.message);
    }

    this.isLive && setTimeout(this.run.bind(this), 300)
  }

  // 游戏初始化
  init() {
    // 绑定键盘按键按下的事件
    document.addEventListener('keydown', this.keydownHandler.bind(this));
    this.run();
  }
  // 键盘按下的响应事件
  keydownHandler(event: KeyboardEvent) {
    /**
     * ArrowUp
       ArrowLeft  
       ArrowRight
       ArrowDown
     */
    // 修改属性
    this.direction = event.key;
  }

  // 检车是否吃到食物
  checkFood() {
    if (this.foods.X === this.snake.X && this.foods.Y === this.snake.Y) {
      // 刷新食物位置
      this.foods.change()
      // 分数增加
      this.scorePanel.add()
      // 蛇增加一节
      this.snake.addBody()
    }
  }
}

export default GameControl;